package com.ustarlink.learnlauncher;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;

import java.util.List;

public class MainActivity extends Activity {
    DrawerAdapter drawerAdapterObject;
    GridView drawerGrid;
    RelativeLayout homeView;
    SlidingDrawer slidingDrawer;
    class Pac{
        Drawable icon;
        String name;
        String label;
    };
    Pac[] pacs;
    PackageManager pm;
    static boolean appLaunchable = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawerGrid = (GridView) findViewById(R.id.content);
        homeView = (RelativeLayout) findViewById(R.id.home_view);
        slidingDrawer = (SlidingDrawer) findViewById(R.id.drawer);
        pm = getPackageManager();

        setPacs();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        filter.addDataScheme("package");
        registerReceiver(new PacRecevier(), filter);


    }

    public void setPacs() {
        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> pacsLsit = pm.queryIntentActivities(mainIntent, 0);
        pacs = new Pac[pacsLsit.size()];
        for (int i = 0; i< pacsLsit.size(); i++ ){
            pacs[i] = new Pac();
            pacs[i].icon = pacsLsit.get(i).loadIcon(pm);
            pacs[i].name = pacsLsit.get(i).activityInfo.packageName;
            pacs[i].label = pacsLsit.get(i).loadLabel(pm).toString();
        }
        new SortApps().exchangeSort(pacs);
        drawerAdapterObject = new DrawerAdapter(this, pacs);
        drawerGrid.setAdapter(drawerAdapterObject);
        drawerGrid.setOnItemClickListener(new DrawerClickListener(this, pacs, pm));
        drawerGrid.setOnItemLongClickListener( new DrawerLongClickListener(this, slidingDrawer, homeView));

    }

    public class PacRecevier extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            setPacs();
        }
    }
}
